<template>
  <div class="video_resource_container">
    <el-row>
      <el-col :span="24">
        <el-button type="primary" @click="handleClick(null, 0, '新增资源')"
          >新增</el-button
        >
        <el-dialog
          :title="dialogTitle"
          :visible.sync="dialogVisible"
          :before-close="resourceFormHandleClose"
          width="40%"
        >
          <el-form
            label-position="left"
            label-width="100px"
            :model="resourceForm"
            :rules="rules"
            ref="resourceForm"
          >
            <el-form-item label="上传方式">
              <el-radio v-model="uploadMethod" label="0">本地上传</el-radio>
              <el-radio v-model="uploadMethod" label="1">腾讯路径</el-radio>
            </el-form-item>
            <el-form-item
              v-if="uploadMethod === '0'"
              label="视频文件"
              prop="url"
            >
              <el-input
                v-if="resourceForm.url"
                :disabled="true"
                v-model="resourceForm.url"
              />
              <FileFragmentUpload
                v-if="dialogVisible && !resourceForm.url"
                @success="uploadResSuccess"
              />
            </el-form-item>
            <el-form-item v-if="uploadMethod === '1'" label="腾讯视频路径">
              <el-input
                v-model="txUrl"
                clearable
                style="width: 75%; margin-right: 10px"
              />
              <el-button
                :loading="txLoading"
                @click="getInfoByTxUrl()"
                type="primary"
                icon="el-icon-search"
                >搜索</el-button
              >
            </el-form-item>
            <el-form-item
              v-if="
                uploadMethod === '1' &&
                this.txResource &&
                this.txResource.length > 0
              "
              label="资源选择"
            >
              <el-checkbox-group v-model="checkedTxResource">
                <el-checkbox
                  v-for="city in txResource"
                  :disabled="isExistDefinition(city.definition)"
                  :label="city"
                  :key="city.url"
                  >{{ city.definitionDesc }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
            <el-form-item
              v-if="resourceForm.url"
              label="文件类型"
              prop="contentType"
            >
              <el-input :disabled="true" v-model="resourceForm.contentType" />
            </el-form-item>
            <el-form-item
              v-if="resourceForm.url"
              prop="definition"
              label="清晰度"
            >
              <el-radio
                v-for="item in definitionOptions"
                :key="item.id"
                :disabled="isExistDefinition(item.value)"
                v-model="resourceForm.definition"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-form-item>
            <el-form-item v-if="resourceForm.status" label="资源状态">
              <el-tag disable-transitions>{{
                getResourceStatusLabel(resourceForm.status)
              }}</el-tag>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button
              v-if="formType !== 1"
              :loading="loading"
              type="primary"
              @click="confirmHandel('resourceForm')"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-table
          :data="pagination.resourceDatas"
          style="width: 100%; margin-bottom: 20px"
          row-key="id"
          border
        >
          <el-table-column type="index" width="30px"></el-table-column>
          <el-table-column prop="url" label="路径"></el-table-column>
          <el-table-column
            prop="contentType"
            label="文件类型"
          ></el-table-column>
          <el-table-column prop="definition" label="清晰度" width="100px">
            <template slot-scope="scope">
              <el-tag disable-transitions>{{
                getDefinitionLabel(scope.row.definition)
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100px">
            <template slot-scope="scope">
              <el-tag disable-transitions>{{
                getResourceStatusLabel(scope.row.status)
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="150px">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.status === '0'"
                @click="resourceTranscode(scope.row)"
                type="text"
                size="small"
                >转码</el-button
              >
              <el-button
                v-if="scope.row.status === '2'"
                @click="
                  playerVisible = true;
                  playUrl = scope.row.url;
                "
                type="text"
                size="small"
                >预览</el-button
              >
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="delResource(scope.row.id)"
              >
                <el-button
                  slot="reference"
                  style="margin-left: 10px"
                  v-if="scope.row.status !== '1'"
                  type="text"
                  size="small"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="pagination.pageSizeChoose"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        ></el-pagination>
      </el-col>
    </el-row>
    <el-dialog :visible.sync="playerVisible" width="30%">
      <Player v-if="playerVisible" :url="playUrl" />
      <span slot="footer" class="dialog-footer"> </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPaginationList,
  addVideoResource,
  addTxVideoResource,
  transcode,
  delResource,
} from "@/api/video/resource";
import { getInfoByTxUrl } from "@/api/video/info";
import FileFragmentUpload from "./FileFragmentUpload";
import Player from "../player";
export default {
  name: "Administrator",
  components: {
    FileFragmentUpload,
    Player,
  },
  created() {
    this.getPaginationVideoResource();
    this.getDictList({ type: "video_resource_status" }).then((res) => {
      this.statusOptions = res.data;
    });
    this.getDictList({ type: "video_definition" }).then((res) => {
      this.definitionOptions = res.data;
    });
  },
  props: {
    dramaSeries: {
      required: true,
    },
  },
  data() {
    return {
      txLoading: false,
      txUrl: "",
      txResource: [],
      checkedTxResource: [],
      playUrl: "",
      uploadMethod: "0",
      playerVisible: false,
      statusOptions: [],
      definitionOptions: [],
      formType: 0,
      loading: false,
      dialogVisible: false,
      dialogTitle: "",
      resourceForm: {
        files: [],
        videoDraId: this.dramaSeries.id,
        url: "",
        contentType: "",
        definition: null,
        status: null,
        bucketName: "",
        objectName: "",
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        pageSizeChoose: [5, 10, 15, 20],
        total: 0,
        resourceDatas: [],
      },
      rules: {
        definition: [
          { required: true, message: "请选择清晰度", trigger: "change" },
        ],
        url: [{ required: true, message: "请上传视频文件", trigger: "blur" }],
      },
    };
  },

  watch: {
    dialogVisible: function () {
      if (this.dialogVisible === false) {
        if (this.uploadMethod === "0") {
          this.$refs["resourceForm"].resetFields();
        } else if (this.uploadMethod === "1") {
          this.txUrl = "";
          this.txResource = [];
          this.checkedTxResource = [];
        }
      }
    },
  },
  methods: {
    isExistDefinition(item) {
      var a = false
      for (var i = 0; i < this.pagination.resourceDatas.length; i++) {
        if (this.pagination.resourceDatas[i].definition === item) {
          a = true;
        }
      }
      return a
    },
    getInfoByTxUrl() {
      this.txLoading = true;
      this.txResource = [];
      getInfoByTxUrl(this.resourceForm.videoDraId, this.txUrl)
        .then((v) => {
          this.txResource = v.data;
          this.checkedTxResource = [];
          // this.checkedTxResource.push(this.txResource[0]);
          this.$message({
            message: "获取资源成功",
            type: "success",
          });
          this.txLoading = false;
        })
        .catch(() => {
          this.$message({
            message: "获取资源失败：请检查地址是否正确，或联系管理员",
            type: "error",
          });
          this.txLoading = false;
        });
    },
    delResource(id) {
      delResource(id).then(() => {
        this.$message({
          message: "删除成功",
          type: "success",
        });
        this.getPaginationVideoResource();
      });
    },
    resourceFormHandleClose() {
      if (!this.resourceForm.id) {
        this.$confirm("还未新增成功，确认关闭？")
          .then(() => {
            this.dialogVisible = false;
          })
          .catch(() => {});
      }
    },
    resourceTranscode(param) {
      transcode(param.id).then(() => {
        this.getPaginationVideoResource();
      });
    },
    uploadResSuccess(res) {
      this.resourceForm.url = res.objectName;
      this.resourceForm.contentType = res.contentType;
      this.resourceForm.bucketName = res.bucketName;
      this.resourceForm.objectName = res.objectName;
    },
    getResourceStatusLabel(value) {
      let ss = "";
      this.statusOptions.forEach((item) => {
        if (item.value === value) {
          ss = item.label;
        }
      });
      return ss;
    },
    getDefinitionLabel(value) {
      let ss = "";
      this.definitionOptions.forEach((item) => {
        if (item.value === value) {
          ss = item.label;
        }
      });
      return ss;
    },
    addTxVideoResource() {
      // const params = {'videoResources': this.checkedTxResource};
      addTxVideoResource(this.checkedTxResource)
        .then(() => {
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.dialogVisible = false;
          this.loading = false;
          this.getPaginationVideoResource();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    addVideoResource() {
      addVideoResource(this.resourceForm)
        .then(() => {
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.dialogVisible = false;
          this.loading = false;
          this.getPaginationVideoResource();
        })
        .catch(() => {
          this.loading = false;
        });
    },

    confirmHandel(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formType === 0) {
            if (this.uploadMethod === "1") {
              this.addTxVideoResource();
            } else if (this.uploadMethod === "0") {
              this.addVideoResource();
            }
          }
          this.loading = true;
        }
      });
    },
    getPaginationVideoResource() {
      const params = {
        pageSize: this.pagination.pageSize,
        pageIndex: this.pagination.currentPage,
        videoDraId: this.resourceForm.videoDraId,
      };
      getPaginationList(params).then((res) => {
        this.pagination.resourceDatas = res.data.records;
        this.pagination.total = res.data.total;
      });
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
    },
    handleClick(data, type, title) {
      if (type !== 0) {
        this.resourceForm = data;
      } else {
        this.resourceForm.checkRoleIds = [];
      }
      this.dialogTitle = title;
      this.formType = type;
      this.dialogVisible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.menu-container {
  .el-row {
    margin-bottom: 20px;
  }
}
</style>